var express = require('express');

var fs = require('fs');

var router = express.Router();

var crypto = require('crypto');

var upload = require('../module/multer');

var CheckLogin = require('../module/checkLogin');

var module_collection = require('../module/database');

var User = module_collection.User;

var Subscribe = module_collection.Subscribe;


var Theme = module_collection.Theme;

var Subscribe = module_collection.Subscribe;

var MyComment = module_collection.MyComment;

var MyTheme = module_collection.MyTheme;

var History = module_collection.History;


function randomWord(randomFlag, min, max) {
    var str = "",
        range = min,
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

    if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
        var pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
    }
    return str;
}

router.post('/register', function (req, res) {

    var user_id = randomWord(true, 8, 8);
    var password = req.body.psw;
    var phone = req.body.phone;
    console.log(phone);
	console.log(password)
    var md5 = crypto.createHash('md5');
    password = md5.update(password).digest('hex')

	console.log(phone);
	console.log(password)
    User.findOne(function (err, data) {
        var user = new User({
            id: user_id,
            phone: phone,
            psw: password,
            permission:1
        });
        User.findOne({
            phone: phone
        }, function (err, data) {
            //console.log(arguments);
            if (err) {
                console.log('查询失败');
                res.send('数据查询失败');
            } else {
                if (data == null) {
                    //存储
                    user.save(function (err) {
                        if (err) {
                            console.log('数据存储失败' + err);
                        } else {
                            console.log('数据存储成功');
                           res.status(200).json({
		                        code: 1,
		                        message: '注册成功',
		                        id:user_id
		                    });
                        }
                    });
  							
                } else {
                    res.status(200).json({
                        code: 0,
                        message: '已被抢注'
                    });
                }
            }
        });

    }).sort({
        id: -1
    }).limit(1);

});

router.post('/login', function (req, res) {
    var password = req.body.pwd;
    User.findOne({
        phone: req.body.phone
    }, function (err, data) {
        //console.log(arguments);
        if (err) {
            console.log('查询失败');
            res.send('数据查询失败');
        } else {
            if (data == null) {
                // 用户名不存在
                res.status(200).json({
                    code: 0,
                    message: "用户名不存在"
                });
            } else {

                var md5 = crypto.createHash('md5');
                password = md5.update(password).digest('hex');
                // 判断密码
                if (password == data.psw) {
                    if(data.permission == 0){
                        res.cookie('permission', 0);
                    }
                    res.status(200).json({
                        code: 1,
                        message: "登陆成功",
                        id: data.id
                    });
                } else {
                    res.status(200).json({
                        code: 0,
                        message: "密码不一致，重新登录"
                    });
                }
            }
        }
    });
});

router.post('/forgetPsw', function (req, res) {
    var newpsw = req.body.newpsw;
    var phoneNum = req.body.phoneNum;
    User.find({
        phone: phoneNum
    }, function (err, data) {
        if (!err) {
            if (data != null) {
                var md5 = crypto.createHash('md5');
                newpsw = md5.update(newpsw).digest('hex');
                User.update({
                    phone: phoneNum
                }, {
                    psw: newpsw
                }, function (err) {
                    if (!err) {
                        res.status(200).json({
                            code: 1,
                            message: '重置密码成功'
                        });
                    } else {

                    }
                });
            } else {
                res.status(200).json({
                    code: 0,
                    message: '用户不存在'
                });
            }
        }

    })
    console.log(newpsw);
});

router.post('/update', function (req, res) {
    User.findOne({
        user_id: req.user_id
    }, function (err, data) {
        //console.log(arguments);
        if (err) {
            console.log('查询失败');
            res.send('数据查询失败');
        } else {
            if (data == null) {
                // 用户名不存在
                res.status(200).json({
                    code: 0,
                    message: '用户不存在'
                });
            } else {
                // 判断密码
                if (req.query.psw == data.psw) {
                    // 修改
                    //把姓名为：张三的 年龄改为：100
                    User.update({
                        username: req.query.username
                    }, {
                        psw: req.query.newpsw
                    }, function (err, result) {
                        //console.log(arguments);
                        if (err) {
                            res.status(200).json({
                                code: 0,
                                message: '修改失败'
                            });
                        } else {
                            res.status(200).json({
                                code: 1,
                                message: '修改成功'
                            });
                        }
                    });
                } else {
                    res.status(200).json({
                        code: 0,
                        message: '密码错误'
                    });
                }
            }
        }
    });
});


router.get('/subscribe', CheckLogin, function (req, res) {
    var user_id = req.cookies.wcID;
    var theme_id = req.query.sectionId;
    var isSub = req.query.isSub;
    console.log(user_id + 'uer');
    console.log(theme_id + 'theme');
    Theme.findOne({
        id: theme_id
    }, function (err, data) {
        var subscribe = new Subscribe({
            user_id: user_id,
            theme_id: theme_id,
            update: "false",
            theme_info: data._id
        });
        subscribe.save(function (err, data) {
            if (!err) {
                console.log(data);
                res.status(200).json({
                    code: 0,
                    message: "订阅成功"
                });
            } else {
                console.log(err.message);
                res.status(200).json({
                    code: 0,
                    message: err,
                    message
                });
            }
        });

    })
})

router.get('/history', function (req, res) {
    var user_id = req.cookies.wcID;
    var history_list = req.query.history_list;
    var array = [];
    var array_loc = [];
    var page = req.query.page;
    console.log(history_list);
    if (history_list == undefined) {
        if (user_id != undefined) {
            History.find({
                user_id: user_id
            }, function (err, data) {
                for (var i = 0; i < data.length; i++) {
                    (function (data) {
                        array_loc.push(data);
                    })(data[i].theme_id);
                }
                res.status(200).json({
                    data: data,
                    list: array_loc
                });
            }).populate('theme_info').populate('user_info');
        }
    } else {
        var length = history_list.length;
        for (var i = 0; i < length; i++) {
            array.push(parseInt(history_list.shift()));
        }
        Theme.find(function (err, data) {
            if (user_id != undefined) {
                History.remove({
                    user_id: user_id
                }, function (err, data) {
                    if (!err) {
                        console.log('历史记录全部删除成功');
                    } else {
                        console.log(err.message);
                    }
                })
                var arr = [];
                var length = data.length;
                for (var i = 0; i < length; i++) {
                    (function (result, user_id, i, arrlen) {
                        var history = new History({
                            user_id: user_id,
                            theme_id: result.id,
                            theme_info: result._id
                        });
                        history.save(function (err, saveData) {
                            arr.push(saveData);
                            if (i == arrlen - 1) {

                            }
                        });
                    })(data[i], user_id, i, length)
                }
                Theme.count(function(err,count){
                    res.status(200).json({
                        data: data,
                        user_id: user_id,
                        total: Math.ceil(count / 10)
                    });
                }).where('id').in(array);

            } else {
                res.status(200).json({
                    data: data,
                    user_id: user_id
                });
            }
        }).where('id').in(array);
    }

});

router.post('/uploadPhoto', upload.single('userPhoto'), function (req, res) {
    var user_id = req.cookies.wcID;
    var img_url = '';
    console.log(req.file);
    console.log(req.body.icon_url);
    if (req.body.icon_url) {
        img_url = req.body.icon_url;
    } else {
        var file = req.file;
        var fileformat = (file.filename).split('.');
        var fileName = fileformat[0];
        var fileType = fileformat[fileformat.length - 1];
        img_url = '/uploads/' + file.filename;
    }

    User.update({
        id: user_id
    }, {
        img_url: img_url
    }, function (err, data) {
        if (!err) {
            res.status(200).json({code:2})
        } else {
            console.log(err.message);
        }

    })
})

router.get('/logout', function (req, res) {

    res.cookie('wcID', '', {
        maxAge: -1
    });
    res.cookie('permission', '', {
        maxAge: -1
    });

    res.status(200).json({
        code: 1,
        message: '注销成功'
    });
});

router.get('/historyNotes', function (req, res) {
    var user_id = req.cookies.wcID;
    console.log(user_id);
    MyTheme.count({
        user_id: user_id
    }, function (err, data) {
        var myTheCount = data;
        MyComment.count({
            user_id: user_id
        }, function (err, data) {
            var myComCount = data;
            Subscribe.count({
                user_id: user_id
            }, function (err, data) {
                var subCount = data;
                History.count({
                    user_id: user_id
                }, function (err, data) {
                    var hisCount = data;
                    console.log(myTheCount);
                    console.log(myComCount);
                    console.log(subCount);
                    console.log(hisCount);
                    res.status(200).json({
                        myTheCount: myTheCount,
                        myComCount: myComCount,
                        subCount: subCount,
                        hisCount: hisCount
                    })
                })
            });
        });
    });





});

router.post('/settingUPhoto', function (req, res) {
    var fileName = 'public/iconUrl.json'
    //  var type = req.body.type;
    fs.readFile(fileName, {
        flag: 'r+',
        encoding: 'utf8'
    }, function (err, data) {
        if (err) {
            console.error(err.message);
            return;
        }
        data = JSON.parse(data);
        console.log(data);
        res.status(200).json({
            data: data
        });
    });
})

router.get('/profile', function (req, res) {
    var user_id = req.cookies.wcID;
    User.find({
        id: user_id
    }, function (err, data) {
        if (!err) {
            res.status(200).json({
                img_url: data[0].img_url
            });
        }
    })
})

function photoUpload(file) {
    if (file) {
        var file = file;
        if (file.mimetype == 'image/jpeg') {
            console.log('格式为JPG');
        }
        var fileformat = (file.filename).split('.');
        var fileName = fileformat[0];
        var fileType = fileformat[fileformat.length - 1];
        img_url = '/uploads/' + file.filename;
    }
}

module.exports = router;